import router from "@/router";
import {getTitle, getToken, noBug, removeAuthInfo} from "@/utils/common";
import useUserStore from "@/store/user";
import {message} from "ant-design-vue";

const whiteList = ["/login"];

if (import.meta.env.MODE == "development") {
  window.configGlobal = import.meta.env;
  // noBug();
}

router.beforeEach(async (to, from, next) => {
  //设置网页标题
  document.title = getTitle(to.meta.title);
  let token = getToken();
  if (token) {
    //有token
    if (to.path == "/login") {
      next({path: "/"});
    } else {
      if (!useUserStore.authMenus || !useUserStore.authMenus.length) {
        let {routes}: {routes: any} = await useUserStore.getLoginUser();
        if (!routes || !routes.length) {
          message.error("暂无权限,请联系管理员");
          removeAuthInfo();
          next({path: "/login"});
        }
        router.options.routes = routes;
        routes.forEach((item: any) => {
          router.addRoute(item);
        });
        let allRoutes = router.getRoutes();
        let toPathHave = allRoutes.some((route) => {
          return route.path == to.path;
        });
        if (toPathHave) {
          //访问的地址有的话 就放行
          next({...to, replace: true});
        } else {
          //访问的地址没有的话 就重定向到第一个页面
          next({path: routes[0].path, replace: true});
        }
      } else {
        if (!useUserStore.userInfo.id) {
          useUserStore.getUserInfo();
        }
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      //属于白名单
      next();
    } else {
      next({path: "/login"});
    }
  }
});
